package top.kaoshanji.q1ch07c;

import top.kaoshanji.y1constant.FileConstant;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 代码清单-q1ch07c-357页a：使用（内存）映射创建超大文件
 * author kaoshanji
 * ^_^
 * create time 2025/3/12 19:08
 */
public class LargeMappedFiles {

    static int length = 0x8000000; // 128 MB
    static String pathStr = FileConstant.LOCAL_ROOT_PATH.concat("q1ch07c357页a\\test.dat"); // 此文件大小 128M

    public static void main(String[] args) {

        try (RandomAccessFile tdat = new RandomAccessFile(pathStr, "rw")){

            // 内存映射文件
            MappedByteBuffer out = tdat.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
            for (int i = 0; i < length; i++) {
                out.put((byte) 'x');
            }

            System.out.println("Finished writing");

            for (int i = length/2; i < length/2 + 6; i++) {
                System.out.print((char)out.get(i));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
